package com.css.fxfzaqbz.util;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author Dbj
 * @date 2022年08月01日  15:54
 */
@Data
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 清空redis
     */
    public void removeKeyContains(String pattern) {
        Set<String> keys = this.redisTemplate.keys(pattern);
        if (keys!=null && keys.size() > 0) {
            this.redisTemplate.delete(keys);
        }
    }

    /**
     * 从redis中删除指定的key
     */
    public void removeCache(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 从redis中获取指定key的value值
     */
    public  <T> T  getCache(String key) {
        Object value = redisTemplate.opsForValue().get(key);
        return (T)value;
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key) != null;
    }

    /**
     * 添加缓存
     *
     * @param key    key
     * @param value  value
     * @author qiangchao
     **/
    public void setCacheMap(String key, Object value) {
        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(value));
    }
}
